// 对话窗口
<template>
    <div>
        <div class="chatRoomBox flex" :class="{chatRoomBox_type0:$store.state.userInfo.member_type_int == 0}">  
            <div class="chat-room-left">
                <!-- tab框 -->
                <div class="chats-tabs-head flex flex-align-center flex-pack-center">
                    <div class="user-tabs flex flex-align-center flex-pack-center" :class="{'tabs-active':isChangeTab == 1}" @click="onChangeTabsFun(1)"><p>用户</p></div>
                    <div class="user-tabs flex flex-align-center flex-pack-center" :class="{'tabs-active':isChangeTab == 2}" @click="onChangeTabsFun(2)"><p>消息列表</p></div>
                </div>
                <!-- 搜索框 -->
                <div class="inputBox flex">
                    <input type="text" placeholder="输入会员名称" v-model.trim="SearchUser">
                    <div class="sousBtn  flex flex-align-center flex-pack-center" @click="onSearchFun"><p>搜索会员</p></div>
                </div>
                <!-- 用户列表 -->
                <div class="chat-userList" v-show="isChangeTab == 1">
                    <!-- 用户列表父级菜单 -->
                    <div  v-for='(item,index) in userList ' :key='index'>
                    <div class="chat-userlist-f flex flex-align-center" @click="onUserListFun(index)">
                        <img :src="(index == isOnFimg)?userListFImgOn:userListFImg" :class="{'onimg':(index == isOnFimg)}">
                        <p class="flex-1" v-if='item.group_type == -1' >上级用户<span>{{item.on_line}}/{{item.total_num}}</span></p>
                        <p class="flex-1" v-if='item.group_type == 0' >普通会员<span>{{item.on_line}}/{{item.total_num}}</span></p>
                        <p class="flex-1" v-if='item.group_type == 1' >主管账户<span>{{item.on_line}}/{{item.total_num}}</span></p>
                        <p class="flex-1" v-if='item.group_type == 2' >招商账户<span>{{item.on_line}}/{{item.total_num}}</span></p>
                        <p class="flex-1" v-if='item.group_type == 3' >直属账户<span>{{item.on_line}}/{{item.total_num}}</span></p>
                        <div class="newsQ  flex flex-align-center flex-pack-center" v-if='item.un_read_total_num>0'><p>{{item.un_read_total_num}}</p></div>
                    </div>
                    <div v-show="index == isOnFimg">
                    <!-- 用户列表子级菜单 -->
                    <div class="chat-userlist-chan flex flex-align-center" :class="{'chan-active':toUser.id == e.id && toUser.group_id == e.group_id}" @click="onChanActive(e.nickname,e.id,e.group_id,e.total_num,e.un_read_num,e.group_uid)" v-for='(e, i) in item.data' :key='i'>
                        <p class="flex-1" :class="{'nikename_login':e.login_status == 0}" >{{e.nickname}}</p>
                        <div class="newsQ  flex flex-align-center flex-pack-center" v-if='e.un_read_num>0' ><p>{{e.un_read_num}}</p></div>
                    </div>
                    </div>
                    </div>
                </div> <!-- 用户列表结束 -->
                <!-- 消息列表 -->
                <div class="msg-list-box" v-show="isChangeTab == 2">
                    <div class="chat-userlist-chan flex flex-align-center" :class="{'chan-active':toUser.id == item.id && toUser.group_id == item.group_id}" @click="onChanActive(item.name,item.id,item.group_id,item.total_num,item.un_read_num,item.group_uid)" v-for='(item,index) in msgUserList' :key='index'>
                        <p class="flex-1">{{item.name}} <span v-if="item.total_num != '' && item.total_num != undefined">({{item.total_num}}人)</span></p>
                        <div class="newsQ  flex flex-align-center flex-pack-center" v-if='item.un_read_num>0'><p>{{item.un_read_num}}</p></div>
                    </div>
                </div>
                <!-- 搜索结果展示框 -->
                <div class="seachUserBox" v-if='isSeach'>
                    <div class="chat-userlist-chan flex flex-align-center" v-for='(item,index) in SearchUserList' :class="{'chan-active':toUser.id == item.id  || indexId == item.id}"  :key='index' @mouseenter='onShowDel(item.id)' @mouseleave='indexId = -1' @click="onChanActive(item.nickname,item.id,item.group_id,item.total_num,item.un_read_num,item.group_uid)">
                         <p class="flex-1">{{item.nickname}}</p>
                    </div>
                </div>
            </div>
            <!-- chat-room-right -->
            <div class="chat-room-right">
                <div class="room-right-head flex flex-align-center">
                    <p class="flex-1">{{toUser.name}}</p>
                    <img v-if="toUser.group_id != undefined && toUser.group_id !='' && toUser.group_id != '-1' && !isOrdinary" class="imgBtn" src="@/assets/img/chat-room/qunyuanguanli.png" alt="" @click="adminGroup">
                    <img  v-if="(toUser.group_id == undefined || toUser.group_id=='' || toUser.group_id == '-1') && (toUser.id != undefined && toUser.id != '')" src="@/assets/img/chat-room/gting.png" alt="" >
                </div>
                 <!-- 会员等级不够时提示条 -->
                <div class="errTipsBox flex flex-align-center flex-pack-center" v-if="isOrdinary">
                    <p>你无权限在群聊里回复消息，可私聊上级管理员！<span @click="onPrivatechatFun">立即去私聊</span></p>
                </div>
                <!-- 消息窗体 -->
                <div class="mgsBox" id='data-list-content'>
                    <div class="item clearfix" v-for="(item,index) in msgList" :key='index' >
                        <div class="time">{{item.create_time | time}}</div>
                        <div class="msg" onselectstart="return false" :class="{msg_self:item.from_uid == $store.state.userInfo.id || item.send_uid == $store.state.userInfo.id}" v-html='item.content'></div>
                    </div>
                </div>
                <!-- 发送框 -->
                <div class="sendMsgBox" v-if="!isOrdinary">
                    <div class="sendMsgBoxImg flex flex-align-center">
                        <img src="@/assets/img/chat-room/biaoqing.png" alt="" @click="onOpenFun" v-if='!isOPenWin'>
                         <img src="@/assets/img/chat-room/bqkopen.png" alt="" @click="onOpenFun" v-if='isOPenWin'>
                    </div>
                    <editDiv :value='textCont' v-on:input="deleteFun" @click="clousWinFun"></editDiv>
                    <div class="senBtn flex flex-align-center flex-pack-center" @click="sendMsgFun" :class="{send_type0:$store.state.userInfo.member_type_int == 0}">
                        <p>发送</p>
                    </div>
                    <!-- 表情框 -->
                    <div class="expression-box" v-show="isOPenWin">
                        <img src="@/assets/img/business/business-close.png" alt="" class="clous" @click="clousWinFun">
                        <div class="clearfix emojiBox">
                           <div class="msgImgBox flex" v-for='(item,index) in msgImgList' :key='index'>
                                <img :src="item.url" alt="" @click="addIM_emoji(item.name)">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import {format,uuid} from '@/public/tools';
import https from '@/public/https';
import IM_emojiData from '@/assets/js/IM_emojiData'
import {vodEmotion2Local} from '@/assets/js/IM_emojiTools'
import editDiv from './editDiv.vue'
import IM_conf from '@/assets/js/IM_config'
export default {
    components:{
        editDiv
    },
    data () {
        return {
            isChangeTab:1, 
            userListFImgOn:'./static/img/chatroom/chat-room-arrbottom.png',
            userListFImg:'./static/img/chatroom/chatroom-arrright.png',
            isOnFimg:0, //判断用户列表父级菜单是否点击
            isOPenWin:false,
            msgImgList:IM_emojiData.data, //表情list
            isOrdinary:false, //判断是否为群主
            SearchUser:'', //搜索用户名
            text_cont:'', //消息内容
            typeN:1, // 管理群标识
            SearchUserList:[], //搜索列表
            isSeach:false, //搜索框是否显示
            indexId:'',
        }
    },
    mounted () {
        if(this.$store.state.userInfo.superior == 0){ //用户无权限，无下级时；
                    this.https("Chat/postObtainUserParentInfo",{uid:this.loginInfo},'post')
                    .then(data => {
                        let root = [];
                        let res_on_line = 0;
                        if(data.login_status == 1){
                            res_on_line = 1;
                        } 
                        root.push(data);
                        let res = {
                            '0':{
                                data:root,
                                group_type:-1,
                                on_line:res_on_line,
                                total_num:1,
                                un_read_total_num: data.un_read_num,
                            }
                        }
                        this.$store.commit('setUserList',res);
                    })
        }else{
            // 默认打开聊天室 好友列表
            this.https("chat/postDirectlyUnderUserList",{uid:this.loginInfo},'post')
                    .then(data => {
                    this.$store.commit('setUserList',data);
                })  
        }
    },
    filters:{
        time(date){
           return format(date);
        },
    },
    computed: {
       userList(){ //获取用户列表
           return this.$store.getters.getUserList;
       },
       msgUserList(){ //获取消息用户列表
            return this.$store.getters.getMsgUserList;
       },
       msgList(){ //获取消息列表
           let reg = new RegExp('\\[(.+?)\\]',"g");
           let list =  this.$store.getters.getMsgList;
           for(var i in list){
              list[i].content =  list[i].content.replace(reg,"<img style='height: 0.2rem;width: auto;' src='static/img/chatroom/IM_emoji/$1.png'>");
           }
           return list;
       },
       loginInfo(){ //获取用户信息
          return this.$store.getters.getUserInfo.id;
      },
      toUser(){ //获取要发送的用户信息
          return this.$store.getters.getToUserInfo;
      },
      textCont(){
          let reg = new RegExp('\\[(.+?)\\]',"g");
          let str =  this.text_cont.replace(reg,"<img style='height: 0.2rem;width: auto;' src='static/img/chatroom/IM_emoji/$1.png'>");
          return str;
      }
    },
    watch: { //监听聊天记录数据变化，改变窗体导航条位置
        'msgList':'scrollToBottom',
        SearchUser(news,old){
            if(news == ''){
               this.isSeach = false;
            }
        }
    },
    methods: {
        onChangeTabsFun(val){ //点击tab切换
           if(val == 1){ //用户列表
                this.isChangeTab = 1;
                if(this.$store.state.userInfo.superior == 0){ //用户无下级时；
                    this.https("Chat/postObtainUserParentInfo",{uid:this.loginInfo},'post')
                    .then(data => {
                        let root = [];
                        let res_on_line = 0;
                        if(data.login_status == 1){
                            res_on_line = 1;
                        } 
                        root.push(data);
                        let res = {
                            '0':{
                                data:root,
                                group_type:-1,
                                on_line:res_on_line,
                                total_num:1,
                                un_read_total_num: data.un_read_num,
                            }
                        }
                        this.$store.commit('setUserList',res);
                    })
                }else{
                    this.https("chat/postDirectlyUnderUserList",{uid:this.loginInfo},'post')
                    .then(data => {
                        this.$store.commit('setUserList',data);
                    })
                }
           }else if(val == 2){ //消息列表
               this.isChangeTab = 2;
               this.https("chat/postObtainMessageListByUserId",{uid:this.loginInfo},'post')
               .then(data => {
                   for(let i in data){
                    if(data[i].group_id == -1){
                        data[i].group_id = '';
                    }
                   }
                  this.$store.commit('setMsgUserList',data);
               })
           }
        }, 
        addIM_emoji(name){ //添加聊天表情
            this.text_cont =  this.text_cont+name;
        },
        deleteFun(val){
           this.text_cont = val;
        },
        adminGroup(){ //管理群
             this.$emit('openwin',this.typeN++);
        },
        onSearchFun(){ //搜索
            if(this.SearchUser != ''){
                this.https('chat/postSearchUsersByKeyword',{uid:this.loginInfo,keyword:this.SearchUser})
                .then(data => {
                    this.isSeach = true;
                    this.SearchUserList = data;
                })
            }
        },
        onShowDel(id){
            this.indexId = id;
        },
        onUserListFun(index){ //用户列表 父级点击
            if(index == this.isOnFimg){
                this.isOnFimg = -1;
            }else{
                this.isOnFimg = index;
            }
        },
        scrollToBottom(){ //保持聊天窗口在最底部
            this.$nextTick(() => {
            var div = document.getElementById('data-list-content')
            div.scrollTop = div.scrollHeight
            })
        },
        onChanActive(name,id,group_id,total_num,un_read_num,group_uid){ //用户列表 子级点击
            let text = name;
            let msgUserList = this.msgUserList; //消息用户列表
            let UserList = this.userList; //用户列表
            if(group_id != undefined && group_id !=''){
                text = text+'('+total_num+'人)';
                if(group_uid != this.loginInfo){
                    this.isOrdinary = true;
                }else{
                   this.isOrdinary = false;
                }
            }else{
                 this.isOrdinary = false; 
            }
            if(un_read_num>0){
                for(let i in  msgUserList){ //将消息列表未读改为0;
                    if(msgUserList[i].id == id){
                            msgUserList[i].un_read_num = 0; 
                        }   
                    }
                    for(let i in UserList){ //将用户列表中未读改为0;
                        for(let k in UserList[i].data){
                            if( UserList[i].data[k].id == id){
                                UserList[i].data[k].un_read_num = 0;
                                UserList[i].un_read_total_num = UserList[i].un_read_total_num - un_read_num;
                            }
                        }
                    }
                // 修改总的未读条数
               let unreadnum =  this.$store.state.userInfo.un_read_num - un_read_num;
               this.$store.commit('setAllUnRead',unreadnum);
            }
            this.getNetMessage(this.loginInfo,group_id,id,1);
            let userInfo = {name:text,id:id,group_id:group_id}
            this.$store.commit('setToUserInfo',userInfo);
        },
        getNetMessage(uid,group_id,from_uid,page){ //获取历史消息
            https.post('chat/postObtainMessageRecordLimit',{uid:uid,group_id:group_id,from_uid:from_uid,page})
            .then(data =>{
                if(data.status==1){
                    let root = [];
                    for(var i = data.data.data.length-1;i>=0;i--){
                        root.push(data.data.data[i]);
                    }
                    this.$store.commit('setAllMsgList',root);
                    https.post('chat/postUpdateMessageStatus',{uid:uid,group_id:group_id,from_uid:from_uid})
                    .then(data => {
                        if(data.status == 0){
                            console.log('错误信息：', data.message);
                        }
                    });
                }else{
                    console.log('错误信息：', data.message);
                }
            })
        },
        onOpenFun(){ //打开表情窗口
             this.isOPenWin = ! this.isOPenWin;
        },
        clousWinFun(){ //关闭表情框
            this.isOPenWin = false;
        }, 
        onChangeFun(){ //文本框点击
            this.isOPenWin = false;
        },
        onPrivatechatFun(){ //普通会员私聊上级
            let uid = this.$store.state.userInfo.id;
            this.https('Chat/postObtainUserParentInfo',{uid:uid})
            .then(data => {
                 this.getNetMessage(uid,'',data.id,1);
                 let userInfo = {name:data.nickname,id:data.id,group_id:''}
                 this.$store.commit('setToUserInfo',userInfo);
                 this.isOrdinary = false;
            });
        },
        sendMsgFun(){ //发送消息
            this.text_cont = vodEmotion2Local(this.text_cont);
            let fingerprint = uuid(); // 生成消息指纹
            let _self = this;
            if(_self.text_cont != '' && (_self.toUser.id || _self.toUser.group_id)){
                   let p = createCommonData4(`一对一消息:${IMSDK.getLoginInfo().loginUserId}发送给${_self.toUser.id}`, IMSDK.getLoginInfo().loginUserId, _self.toUser.id,-1,null,fingerprint);
                    // 发送群消息
                    if(this.toUser.group_id){
                        // 根据群id获取群成员
                        https.post('chat/postObtainGroupChatMembers',{group_id:_self.toUser.group_id,uid:IMSDK.getLoginInfo().loginUserId})
                        .then(data => {
                           if(data.status == 1){
                               let userDate = data.data;
                               _self.postAddGroupChatMessageRecord(p,function(res){
                                   if(res){
                                        for(let i in userDate){ //Node IM服务器分发消息
                                        if(userDate[i].uid != IMSDK.getLoginInfo().loginUserId){
                                            p = createCommonData4(`群消息:${IMSDK.getLoginInfo().loginUserId}发送给${userDate[i].uid}`, IMSDK.getLoginInfo().loginUserId,userDate[i].uid,_self.toUser.group_id,null,fingerprint);
                                            IMSDK.sendData(p);
                                        }
                                      }
                                    IM_conf.showChatMessage(p, _self.text_cont);
                                      _self.text_cont = '';
                                   }else{
                                        _self.$message({
                                            type:'warning',
                                            message:'保存群消息失败，群消息发送失败！'
                                        }) 
                                   }
                               })
                           }else{
                                _self.$message({
                                    type:'warning',
                                    message:'获取群成员失败，群消息发送失败！'
                                })
                           }
                        });
                    }else{
                        _self.postAddChatMessageRecord(p,function(res){
                            if(res){
                                IM_conf.showChatMessage(p, _self.text_cont);
                                IMSDK.sendData(p);
                                _self.text_cont = '';
                            }else{
                                _self.$message({
                                    type:'warning',
                                    message:'消息保存失败，一对一消息发送失败!'
                                })
                            }
                        })
                    }
            }else{
                // 消息为空时提示
                this.$message({
                    type:'warning',
                    message:'未选择消息接收人或者消息不能为空!'
                })
            }
        },

        /**
         * 方法：保存群消息
         * 参数：消息内容、保存消息成功的回调
         */
        postAddGroupChatMessageRecord(p,callback){
            var contents = {
                send_uid: p.from,
                content: this.text_cont,
                uid: p.from,
                group_id: this.toUser.group_id,
                fingerprint: p.fp
            };

            https.post('chat/postAddGroupChatMessageRecord',contents)
            .then(data => {
                if(data.status == 1){
                    callback(true)
                }else{
                    callback(false)
                }
            })
        },

        /**
         * 方法：保存一对一消息
         * 参数：消息内容、保存消息成功的回调
         */
        postAddChatMessageRecord(p,callback){
            var contents = {
                from_uid: p.from,
                to_uid: p.to,
                content: this.text_cont,
                uid: p.from,
                fingerprint: p.fp
            };

            https.post('chat/postAddChatMessageRecord',contents)
            .then(data => {
                if(data.status == 1){
                    callback(true)
                }else{
                    callback(false)
                }
            })
        }
    }
}
</script>
<style lang="less" scoped>
@import url(../../../assets/css/chatroom/chatroombox.less);
</style>


